package ecustom.finance.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import ecustom.clients.k3client.K3WebApiClient;
import ecustom.clients.k3client.entities.ERPPAYBILLReq;
import ecustom.clients.k3client.entities.ERPPAYBILLReq.FPAYBILLENTRY;
import ecustom.common.CustomMap;
import ecustom.common.servicelog.bean.ServiceLogBean;
import ecustom.common.util.CustomUtil;
import ecustom.finance.actions.FYLFKAction;
import weaver.file.Prop;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

/**
* @author 作者:Gcc
* @createDate 创建时间：Aug 24, 2023 2:41:46 PM
* 
* 保存费用付款单
* 
* 若币别涉及到外币的情况，则表单上的金额都需要乘以汇率传输给ERP
* 结算本位币：固定人民币
* 
*/
public class SaveFYFKDBean extends FYLFKAction{
	
	public Map<String, Object> handlERPData(RequestInfo requestInfo, Property[] mainFields) throws Exception {
		ServiceLogBean logBean = new ServiceLogBean("FYLFKAction", "ecustom.finance.actions.CLBXAction-费用类付款-保存费用付款单",  "K3Cloud", "", System.currentTimeMillis());
		String formid = Prop.getPropValue("ecustom", "k3.fkd.formid");
		
		ERPPAYBILLReq req = setAYBILLReq(requestInfo, mainFields);
		Map<String, Object> erpResult = K3WebApiClient.saveData(logBean, req, formid);
		return erpResult;
	}
	
	public ERPPAYBILLReq setAYBILLReq(RequestInfo requestInfo, Property[] mainFields) throws Exception, Exception {
		String fqzz = FinanceBean.getERPOrgNumber(super.getMainStringCK(mainFields, "fqzz", "发起组织不能为空！"));	// 所属公司
		String bb = super.getMainStringCK(mainFields, "bb", "币别不能为空！");	// 币别
		String wldw = FinanceBean.getERPWldw(super.getMainStringCK(mainFields, "gys", "供应商不能为空！"), "BD_Supplier");	// 往来单位
		String fyzy = super.getMainString(mainFields, "fyzy");	// 费用摘要
		Double hl = super.getMainDouble(mainFields, "hl");	// 汇率
		
		ERPPAYBILLReq repPUR = new ERPPAYBILLReq();   
		repPUR.setIsAutoSubmitAndAudit("true");	// 审核
		repPUR.getModel().setFID(0);	// 实体主键，有实体主键为修改操作，没有则新建
		repPUR.getModel().getFBillTypeID().put("FNUMBER", "FKDLX09_ZDY");	// 费用付款单
		repPUR.getModel().setFDATE(CustomUtil.getStringDate());	// 单据时间
		repPUR.getModel().setFCONTACTUNITTYPE("BD_Supplier");	// 往来单位类型：固定供应商类型
		repPUR.getModel().getFCONTACTUNIT().put("FNumber", wldw);	// 往来单位：供应商
		repPUR.getModel().setFRECTUNITTYPE("BD_Supplier");	// 收款单位类型：供应商
		repPUR.getModel().getFRECTUNIT().put("FNumber", wldw);	// 收款单位
		repPUR.getModel().getFPAYORGID().put("FNumber", fqzz);	// 付款组织
		repPUR.getModel().getFSETTLEORGID().put("FNumber", fqzz);	// 结算组织
		repPUR.getModel().getFCURRENCYID().put("FNumber", bb);	// 币别
		repPUR.getModel().getFSETTLECUR().put("FNUMBER", bb);	// 结算币别
		repPUR.getModel().getFSETTLEMAINBOOKID().put("FNUMBER", "PRE001");	// 结算本位币，币别
		repPUR.getModel().setF_SZXY_OARequestID(requestInfo.getRequestManager().getRequestid()+"");	// OAID
		repPUR.getModel().setF_SZXY_Combo("2");	// 是否往来费用
		repPUR.getModel().setFREMARK(FinanceBean.delHTMLTag(FinanceBean.subRemark(fyzy)));		// 备注-费用摘要
		
		if(!"PRE001".equals(bb)) {
			repPUR.getModel().setFEXCHANGERATE(hl);	// 汇率
			repPUR.getModel().setFSETTLERATE(hl);	// 汇率
		}
		
		repPUR.getModel().setFDOCUMENTSTATUS("Z");	// 单据状态：固定-Z
		repPUR.getModel().setFBUSINESSTYPE("2");	// 业务类型：固定-2
		repPUR.getModel().setFCancelStatus("A");	// 作废状态，默认：A
		repPUR.getModel().setFPAYBILLENTRY(getFPAYBILLENTRY(requestInfo, mainFields, repPUR));
		return repPUR;
	}
	
	/**
	 * TODO 
	 * 赋值明细表
	 * @param requestInfo
	 * @param mainFields
	 * @param jsfs	结算方式
	 * @param fkyt	付款用途
	 * @return
	 * @throws Exception
	 * @throws Exception
	 */
	public List<FPAYBILLENTRY> getFPAYBILLENTRY(RequestInfo requestInfo, Property[] mainFields, ERPPAYBILLReq repPUR) throws Exception, Exception {
		Integer requestid = requestInfo.getRequestManager().getRequestid();
		int formid = requestInfo.getRequestManager().getFormid();
		String dfyhmc = super.getMainString(mainFields, "dfyhmc");	// 对方账户名称
		String dfyhzh = super.getMainString(mainFields, "dfyhzh");	// 对方银行账号
		String wfyxzh = FinanceBean.getERPYhzh(super.getMainString(mainFields, "yhzh"));	// 收款账号（我方银行账号）
		String yxwd = super.getMainString(mainFields, "yxwd");	// 对方银行网点
		Double hl = super.getMainDouble(mainFields, "hl");	// 汇率
		
		Map<String, Object> maxAmountMap = FinanceBean.getFYLFKMaxAmount(formid, "DT1", requestid);
		String rowId = CustomUtil.getString(maxAmountMap.get("ID"));
		DetailTable  detailTable = requestInfo.getDetailTableInfo().getDetailTable(0);
		List<FPAYBILLENTRY> listFEntity = new ArrayList<FPAYBILLENTRY>();
		for(Row row: detailTable.getRow()) {
			String fycdbm = FinanceBean.getERPDeptNumberV2(super.getCellString(row, "fycdbm"));	// 费用承担部门
			String fyxm = FinanceBean.getERPFyxm(super.getCellString(row, "fyxmbm"));	// 费用项目
			Double jshj = super.getCellDoubleValue(row, "jshj") * hl;	// 价税合计
			String bz = super.getCellString(row, "bz");	// 备注
			String bzfph = super.getCellString(row, "bzfph");	// 备注发票号
			String rkqj = super.getCellString(row, "rkqj");	// 费用内容(费用类必须填写)
			
			FPAYBILLENTRY entry = new FPAYBILLENTRY();
			entry.getFSETTLETYPEID().put("FNumber", "JSFS04_SYS");	// 结算方式：固定电汇
			entry.getFPURPOSEID().put("FNumber", "SFKYT09_SYS");	// 付款用途：固定预付款
			if(CustomUtil.isNotBlank(fyxm)) {
				entry.getFCOSTID().put("FNumber", fyxm);;	// 费用项目
			}
			if(CustomUtil.isNotBlank(fycdbm)) {
				entry.getFEXPENSEDEPTID_E().put("FNumber", fycdbm);;	// 费用承担部门
			}
			if(CustomUtil.isNotBlank(wfyxzh)) {
				entry.getFACCOUNTID().put("FNumber", wfyxzh);;	// 我方银行账号
			}
			entry.setFOPPOSITEBANKACCOUNT(dfyhzh);	// 对方银行账号
			entry.setFOPPOSITECCOUNTNAME(dfyhmc);	// 对方账户名称
			entry.setFCOMMENT(FinanceBean.subRemark(bz));	// 备注
			entry.setF_SZXY_NoteInvNO(bzfph);	// 备注发票号
			if(CustomUtil.isNotBlank(yxwd)) {
				entry.getFBankDetail().put("FNUMBER", yxwd);	// 银行网点
			}
			
			// 固定值
			entry.setFRecType("0");	// 收款类型：固定企业
			entry.setFPOSTDATE(CustomUtil.getStringDate());	// 登账日期
			entry.setFRuZhangType("1");	// 入账类型：固定并笔入账
			
			// 发票费用明细
			if(CustomUtil.isNotBlank(rowId) && rowId.equals(row.getId())) {
				List<FPAYBILLENTRY> invoiceDetail = handlInvoiceDetail(requestInfo, entry, hl);
				Double sfje = jshj-entry.getF_SZXY_Amount1();	// 价税合计-发票汇总税额
				entry.setF_SZXY_Amount(sfje);	// 价税合计-发票汇总税额
				entry.setFPAYAMOUNTFOR_E(sfje);	// 付款金额:价税合计
				entry.setFPAYTOTALAMOUNTFOR(sfje);	// 应付金额:价税合计
				
				entry.setF_SZXY_Amount1(0.0);	// 最大费用明细不传输进项税
				listFEntity.add(entry);
				listFEntity.addAll(invoiceDetail);	// 将发票费用明细写入到ERP里面
			}else {
				entry.setF_SZXY_Amount(jshj);	// 费用金额
				entry.setFPAYAMOUNTFOR_E(jshj);	// 付款金额:价税合计
				entry.setFPAYTOTALAMOUNTFOR(jshj);	// 应付金额:价税合计
				listFEntity.add(entry);
			}
			
		}
		
		return listFEntity;
	}
	
	/**
	 * 处理发票费用明细
	 * @param invoiceNumbers
	 * @param entry
	 * @param taxSum
	 * @return
	 * @throws Exception
	 */
	private List<FPAYBILLENTRY> handlInvoiceDetail(RequestInfo requestInfo, FPAYBILLENTRY entry, Double hl) throws Exception {
		Double taxSum = 0.0;
		DetailTable  detailTable = requestInfo.getDetailTableInfo().getDetailTable(1);
		List<FPAYBILLENTRY> invoiceDetail = new ArrayList<FPAYBILLENTRY>();
		for(Row row: detailTable.getRow()) {
			String invoiceNumbers = super.getCellString(row, "fphm");
			List<CustomMap> invoiceMap = FinanceBean.getInvoiceData(invoiceNumbers);	// 发票号码
			if(CustomUtil.isNotBlank(invoiceMap)) {
				for(CustomMap map : invoiceMap) {
					Double tax = map.getDouble("DTAX") * hl;
					if(CustomUtil.isNotBlank(tax) && tax > 0) {
						FPAYBILLENTRY newEntry = new FPAYBILLENTRY();
						newEntry.getFSETTLETYPEID().put("FNumber", "JSFS04_SYS");	// 结算方式：固定电汇
						newEntry.getFPURPOSEID().put("FNumber", "SFKYT09_SYS");	// 付款用途：固定预付款
						if(CustomUtil.isNotBlank(entry.getFCOSTID().get("FNumber"))) {
							newEntry.getFCOSTID().put("FNumber", entry.getFCOSTID().get("FNumber"));	// 费用项目
						}
						if(CustomUtil.isNotBlank(entry.getFEXPENSEDEPTID_E().get("FNumber"))) {
							newEntry.getFEXPENSEDEPTID_E().put("FNumber", entry.getFEXPENSEDEPTID_E().get("FNumber"));	// 费用承担部门
						}
						if(CustomUtil.isNotBlank(entry.getFACCOUNTID().get("FNumber"))) {
							newEntry.getFACCOUNTID().put("FNumber", entry.getFACCOUNTID().get("FNumber"));	// 我方银行账号
						}
						
						newEntry.setFOPPOSITEBANKACCOUNT(entry.getFOPPOSITEBANKACCOUNT());	// 对方银行账号
						newEntry.setFOPPOSITECCOUNTNAME(entry.getFOPPOSITECCOUNTNAME());	// 对方账户名称
						newEntry.setFCOMMENT("");	// 备注
						newEntry.setFRecType("0");	// 收款类型：固定企业
						newEntry.setFPOSTDATE(CustomUtil.getStringDate());	// 登账日期
						newEntry.setFRuZhangType("1");	// 入账类型：固定并笔入账
						newEntry.setF_SZXY_NoteInvNO(map.getString("INVOICENUMBER"));	// 备注发票号
						newEntry.setF_SZXY_Amount(null);	// 费用金额
						newEntry.setF_SZXY_Amount1(tax);	// 进项税，传发票的增值税
						newEntry.setFPAYTOTALAMOUNTFOR(null);	// 应付金额
						invoiceDetail.add(newEntry);
						taxSum = CustomUtil.add(taxSum, tax);	// 进项税累加
					}
					
				}
			}
		}
		
		entry.setF_SZXY_Amount1(taxSum);	// 合计进项税，传发票的增值税
		return invoiceDetail;
	}

}
